package com.etonedu.meals.http;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Looper;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.bean.AppBean;
import com.etonedu.meals.bean.Result;
import com.etonedu.meals.common.SPConst;
import com.etonedu.meals.enumeration.APICodeEnum;
import com.etonedu.meals.http.xutils.NewXUtilsRequest;
import com.etonedu.meals.http.xutils.NewXUtilsResponse;
import com.etonedu.meals.utils.SharedPreferencesUtil;
import com.etonedu.meals.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;

public class AppVersionUpdata {

    public static void getPublicUrl(String token) {
        String apiCode = APICodeEnum.agw30161010.getApiCode();

        SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(x.app());
        String type = spu.getString(SPConst.ENVIRONMENT);
//        String environType = EnvironmentType.TEST01.getType();

        String url = spu.getString(SPConst.AGW_30161010);
        if (!Utils.isEmpty(url)) {
            getData(apiCode,url,token);
            return;
        }

        Request request = new Request();
        request.getPublicUrl(apiCode,type);
        request.setGetUrl(new IGetUrl() {
            @Override
            public void success(String content) {
                spu.setString(SPConst.AGW_30161010,content);
                getData(apiCode,content,token);
            }

            @Override
            public void fail(String content) {
                LogUtils.e("content = "+content);

            }
        });
    }

    private static void getData(String apiCode,String content,String token) {

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.http";
        LogReportUtils.log("获取APP版本",pagek,Utils.getLineInfo(),time1);

        String header = ParamsUtils.getHeader(apiCode,token);

        int version = Utils.getVersionCode(x.app());
        String ver = Utils.getVersion1(x.app());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceCode", Utils.getDevCode());
        hashMap.put("verId", version);
        hashMap.put("ver", ver);
        hashMap.put("appType", 4);//1人人通家长版 ，2人人通老师版，3名师课堂版，4新班牌...
        hashMap.put("type", 4);
        Gson gson = new Gson();
        String json = gson.toJson(hashMap);

        String data = ParamsUtils.getEncrypt(apiCode,json);

        String data1 = ParamsUtils.getParams(apiCode,data);

        NewXUtilsRequest request = new NewXUtilsRequest(header, data1);
        request.requet(content,apiCode, HttpMethod.POST,new NewXUtilsResponse(){

            @Override
            public void response(String type, String result) {
                LogUtils.e("result = "+result);

                Type typeToken = new TypeToken<Result>() {
                }.getType();
                Gson gson = new Gson();
                Result r = gson.fromJson(result, typeToken);

                String data = r.getData();

                String deData = ParamsUtils.getDecrypt(apiCode,data);
                LogUtils.e("deData = "+deData);

                Type appType = new TypeToken<AppBean>(){}.getType();
                AppBean appBean = gson.fromJson(deData,appType);
                if (appBean != null) {
                    boolean isForce = appBean.isForce();
                    if (isForce) {

                        String url = appBean.getLastStableUrl();
                        LogUtils.e(url);
                        intoDownloadManager(x.app(),url);
                    }
                }
            }

            @Override
            public void error(String type, String msg) {

            }
        });
    }

    public static void intoDownloadManager(Context context, String url) {

        Toast.makeText(x.app(), "正在更新版本", Toast.LENGTH_LONG).show();

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.http";
        LogReportUtils.log("正在更新版本",pagek,Utils.getLineInfo(),time1);

        // 设置下载路径和文件名

        String yjtAppPath = Utils.getSDPath() + "/yjtApp" + "/" + Utils.getFileName(url);
        File file = new File(yjtAppPath);
        if (file.exists()) {
            file.delete();
        }

        RequestParams params = new RequestParams(url);
        params.setSaveFilePath(yjtAppPath);
        x.http().get(params, new Callback.CommonCallback<File>() {
            @Override
            public void onSuccess(File result) {
                slientInstall(x.app(), result);
                LogReportUtils.log("APP下载完成:地址:"+result.getPath(),pagek,Utils.getLineInfo(),time1);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 静默安装或者弹窗提示安装
    private static void slientInstall(final Context context, final File file) {

        new Thread(new Runnable() {
            @SuppressLint("WrongConstant")
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    if (Utils.slientInstall(file)) {
                        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
                        String pagek = "com.etonedu.general.edu.http";
                        LogReportUtils.log("安装成功:地址:"+file.getPath(),pagek,Utils.getLineInfo(),time1);
                        Toast.makeText(context, "安装成功!", Toast.LENGTH_SHORT).show();
                        Intent intent1 = new Intent();
                        intent1.setClassName("com.etonedu.general.edu", "com.etonedu.general.edu.ui.activity.MainActivity");
                        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent1);
                    } else {
                        // 弹出安装页面
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        install.setDataAndType(Uri.parse(file.getPath()), "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);

                    }
                    Looper.loop();
                } catch (Exception e) {
                    String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
                    String pagek = "com.etonedu.general.edu.http";
                    LogReportUtils.log("安装失败",pagek,Utils.getLineInfo(),time1);
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
